/*
 * udpcli.c
 *
 *  Created on: May 30, 2012
 *      Author: root
 */


#include "unp.h"

#define BUFSIZE 1500
#define randomR(a, b) (rand() % (b-a))+a

void error_handling(char *message);
void make_packet(char *buf);

typedef struct{
	uint16_t len;
	uint16_t seqno;
	char payload[1500];
} Packet;

Packet packet;

int main(int argc, char** argv)
{
	int sock;
	char message[BUFSIZE];
	int str_len, addr_size;

	struct sockaddr_in serv_addr;
	struct sockaddr_in from_addr;

	if(argc != 3){
		printf("Usage: %s <IP><PORT> \n",argv[0]);
		exit(1);
	}

	sock = socket(PF_INET, SOCK_DGRAM, 0);

	if(sock == -1)
		error_handling("socket error");

	memset(&serv_addr, 0, sizeof(serv_addr));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
	serv_addr.sin_port = htons(atoi(argv[2]));

	memset(packet.payload,0,sizeof(packet.payload));
	packet.seqno = 0;

	while(packet.seqno<1000)
	{
		packet.len = 0;
		make_packet(&packet);
		sendto(sock, &packet, BUFSIZE, 0, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
		addr_size = sizeof(from_addr);
		printf("seqno	: %d\n",packet.seqno);
		printf("len	: %d\n",packet.len);
		printf("payload	: %s\n",packet.payload);
		printf("================================\n");
		memset(packet.payload,0,sizeof(packet.payload));
	}
	packet.len = 0;
	packet.seqno = 0;
	memset(packet.payload,0,sizeof(packet.payload));
	sendto(sock, &packet, BUFSIZE, 0, (struct sockaddr*) &serv_addr, sizeof(serv_addr));
	close(sock);
	return 0;
}

void error_handling(char *message)
{
	fputs(message, stderr);
	fputs('\n', stderr);
	exit(1);
}

void make_packet(char *payload)
{
	int i,num,type;
	char buf1[10];

	srand(time(NULL));
	memset(buf1,0,sizeof(buf1));
	type=randomR(1,3);
	//printf("%d", num);
	packet.len = 0;

	if(type == 1)  // 50 byte
	{
		for(i=0;i<46;i++)
		{
			num=randomR(65,90);
			sprintf(buf1,"%c",num);
			strcat(packet.payload, buf1);
			memset(buf1,0,sizeof(buf1));
		}
	}
	else if(type == 2)  // 500 byte
	{
		for(i=0;i<496;i++)
		{
			num=randomR(65,90);
			sprintf(buf1,"%c",num);
			strcat(packet.payload, buf1);
			memset(buf1,0,sizeof(buf1));
		}
	}
	else if(type == 3)  // 1400 byte
	{
		for(i=0;i<1396;i++)
		{
			num=randomR(65,90);
			sprintf(buf1,"%c",num);
			strcat(packet.payload, buf1);
			memset(buf1,0,sizeof(buf1));
		}
	}
	packet.len = strlen(packet.payload)+sizeof(packet.len)+sizeof(packet.seqno);
	packet.seqno++;
	//printf("%d %s",packet.len, payload);
}
